package client;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
 * @author KEM
 * 
 */
class ScreenReceiver extends Thread {

	private ObjectInputStream cObjectInputStream = null;
	private JPanel pScreen = null;
	private boolean loop = true;

	public ScreenReceiver(ObjectInputStream ois, JPanel p) {
		cObjectInputStream = ois;
		pScreen = p;
		start();
	}

    @Override
	public void run() {

		while (loop) {
			try {
				BufferedImage buff = null;				
				byte [] bb = (byte[]) cObjectInputStream.readObject();
				buff = ImageIO.read(new ByteArrayInputStream(bb));
				System.out.println("New image received: " + bb.length);
				Image image = Toolkit.getDefaultToolkit().createImage(buff.getSource());
				image = image.getScaledInstance(pScreen.getWidth(),
						pScreen.getHeight(), Image.SCALE_FAST);
				Graphics graphics = pScreen.getGraphics();
				graphics.drawImage(image, 0, 0, pScreen.getWidth(),
						pScreen.getHeight(), pScreen);
			} catch (IOException ex) {
				ex.printStackTrace();
				loop = false;
			} catch (ClassNotFoundException ex) {
				ex.printStackTrace();
			}
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
